﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using WPFEdit.Util;


namespace WPFEdit.Document.Factory
{
    using TWriterBoolPair = Tuple<IDocumentWriter, bool>;
    
    public class DocWriterFactory : InterfaceFactory< IDocumentWriter, Type, TWriterBoolPair, DocumentWriterAttribute>
    {
        public IDocumentWriter GetDocumentWriter(Type type)
        {
            TWriterBoolPair writer;
            if (m_factoryInstances.TryGetValue(type, out writer))
            {
                return writer.Item1;
            }
            KeyValuePair<Type, TWriterBoolPair> pair = m_factoryInstances.FirstOrDefault<KeyValuePair<Type, TWriterBoolPair>>(keyValpair => (keyValpair.Value.Item2 && keyValpair.Key.IsAssignableFrom(type)));
            if (pair.Value != null)
            {
                return pair.Value.Item1;
            }
            return null;
        }

        protected override void AddType(Type type, object[] attributeInstances, ConstructorInfo constructorInfo)
        {
            foreach (DocumentWriterAttribute writerInfo in attributeInstances)
            {
                m_factoryInstances.Add(writerInfo.DocumentDataType, new Tuple<IDocumentWriter, bool>((IDocumentWriter)constructorInfo.Invoke(Reflection.EmptyObjects), writerInfo.WritesSubclasses));
            }
        }
    }
}
